package def

import (
	"encoding/json"
	"fmt"
	"go/format"
	"log"
	"sort"
	"strings"
)

func GoDef(bs []byte, name string) {
	var data interface{}
	err := json.Unmarshal(bs, &data)
	if err != nil {
		log.Fatal(err)
	}

	if bs, err := format.Source([]byte("type " + strings.Title(name) + " " + goType(data))); err == nil {
		fmt.Println(string(bs))
	} else {
		log.Fatal(err)
	}
}

func goType(data interface{}) string {
	switch val_data := data.(type) {
	case string:
		return "string"
	case bool:
		return "bool"
	case float64:
		if float64(int64(val_data)) == val_data {
			return "int64"
		}
		return "float64"
	case int64:
		return "int64"
	case []interface{}:
		if len(val_data) > 0 {
			return "[]" + goType(val_data[0])
		}
		return "[]interface{}"
	case map[string]interface{}:
		var keys []string
		for i_k := range val_data {
			keys = append(keys, i_k)
		}
		sort.Strings(keys)

		tmp := "struct {\n"
		for _, i_k := range keys {
			tmp = tmp + strings.Title(i_k) + " " + goType(val_data[i_k]) + " `json:\"" + i_k + "\"`\n"
		}
		tmp = tmp + "}"

		return tmp
	default:
		return "interface{}"
	}
}
